package com.yc.star.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.gson.Gson;
import com.yc.star.entity.Friend;
import com.yc.star.entity.Maginform;
import com.yc.star.entity.Team;
import com.yc.star.entity.User;
import com.yc.star.mapper.FriendMapper;
import com.yc.star.mapper.MaginformMapper;
import com.yc.star.mapper.UserMapper;
import com.yc.star.vo.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.server.PathParam;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;

@RestController
@RequestMapping("user")
public class UserDo {

    @Resource
    UserMapper userMapper;

    @Resource
    RedisUtil redisUtil;

    @Resource
    EmailUtil emailUtil;


    @RequestMapping("login")
    public Result login(String email, String phone, String userPassword, HttpSession session) {
        if (StringUtils.isNull(phone) && StringUtils.isNull(email)) {
            return new Result(0, "请输入手机号码或邮箱", null);
        }
        if ((userPassword == null || userPassword.trim().isEmpty())) {
            return new Result(0, "请输入密码", null);
        }
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        if (!StringUtils.isNull(phone)) {
            lqw.eq(User::getPhone, phone);
        }
        if (!StringUtils.isNull(email)) {
            lqw.eq(User::getEmail, email);
        }
        lqw.eq(User::getPassword, userPassword);
        User user = userMapper.selectOne(lqw);
//        System.out.println(user);
        if (user != null) {
            session.setAttribute("loginedUser", user);
            Set<User> onlineUsers = (Set<User>) redisUtil.get("onlineUsers");
            //在线用户
            onlineUsers.add(user);
            redisUtil.set("onlineUsers",onlineUsers);
            //controller层接收数据，生成token，并响应
            Map<String, Object> map = new HashMap<>();
            try {
                Map<String, String> payload = new HashMap<>();
                payload.put("id", user.getId().toString());
                payload.put("name", user.getUsername());
                //生成JWT令牌
                String token = JwtUtil.getToken(payload);
                map.put("state", true);
                map.put("msg", "认证成功");
                map.put("token", token);//响应token
                map.put("loginedUser", user);//用户
//                redisUtil.set(user.getId().toString(),user);
                redisUtil.setT(token, user, 2 * 60 * 60);//将token作为键存入缓存
            } catch (Exception e) {
                map.put("state", "false");
                map.put("msg", e.getMessage());
            }
            return new Result(1, "登陆成功", map);
        }
        return new Result(0, "登陆失败", null);
    }

    /**
     * 用户退出
     *
     * @param uid
     * @param session
     * @return
     */
    @RequestMapping("logout")
    public Result logout(HttpServletRequest request, String uid, HttpSession session) {
        session.removeAttribute("loginedUser");
        String token = request.getHeader("Token");
        System.out.println(token);
        User user = (User) redisUtil.get(token);
        Set<User>  onlineUsers = (Set<User>) redisUtil.get("onlineUsers");
        onlineUsers.remove(user);
        redisUtil.set("onlineUsers", onlineUsers);
//        List<User> onlineUsers = (List<User>) redisUtil.get("OnlineUsers");
//        onlineUsers.remove(user);
//        System.out.println(onlineUsers);
        redisUtil.delete(token);
        return new Result(1, "退出成功", null);
    }

    @RequestMapping("doReg")
    public Result DoReg(String vcode, String email, String phone, String userPassword) {
        if ((vcode == null || vcode.trim().isEmpty())) {
            return new Result(0, "请输入验证码", null);
        }
        if ((phone == null || phone.trim().isEmpty() && email == null || email.trim().isEmpty())) {
            return new Result(0, "请输入手机号码或邮箱", null);
        }
        if ((userPassword == null || userPassword.trim().isEmpty())) {
            return new Result(0, "请输入密码", null);
        }
        Object vcode1 = redisUtil.get("vcode");
        if (!vcode1.toString().equals(vcode)) {
            return new Result(0, "验证码错误", null);
        }
        String uname = "用户";
        User user = new User();
        Object account = redisUtil.get("account");
        account = (int) account + 1;
        user.setUserAccount(account.toString());
        redisUtil.set("account", account);
        user.setPhone(phone);
        user.setPassword(userPassword);
        redisUtil.set(account.toString(), 0);//点赞数
        user.setEmail(email);
        user.setUsername(uname + account);
        int result = userMapper.insert(user);
        if (result == 0) {
            return new Result(0, "注册失败", null);
        }
        return new Result(1, "注册成功", result);
    }


    /**
     * 验证是否登录
     *
     * @param loginedUser
     * @return
     */
    @GetMapping("myInfo")
    public Result myInfo(
            @SessionAttribute(required = false) User loginedUser) {
        if (loginedUser == null) {
            return new Result(0, "未登录", null);
        } else {
            User user1 = userMapper.selectById(loginedUser.getId());
            String tags = user1.getTags();
            //判断用户标签是否为空
            if (tags == null) {
                return new Result(1, "null", user1);
            }
            return new Result(2, "已登录", user1);
        }
    }

    /**
     * 查询用户
     *
     * @return
     */
    @GetMapping("getUser")
    public Result getUser(HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        if (user == null) {
            return new Result(0, "未登录", null);
        } else {
            User user1 = userMapper.selectById(user.getId());
            int like = (Integer) redisUtil.get(user1.getUserAccount());
            user1.setLike(like);
            return new Result(1, "已登录", user1);
        }
    }


    /**
     * 添加用户标签
     *
     * @return
     */
    @RequestMapping("addTag")
    public Result addTag(@RequestBody List<String> tags,
                         HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        System.out.println(tags);
        Gson gson = new Gson();
        String json = gson.toJson(tags);
        System.out.println(json);
        user.setTags(json);
        userMapper.updateById(user);
        return new Result(1, "添加标签成功", null);
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("updateUser")
    public Result updateUser(@RequestBody User user,
                             HttpServletRequest request) {

        String token = request.getHeader("Token");
        User u = (User) redisUtil.get(token);
//
//        System.out.println(user);
//        Gson gson = new Gson();
//        String json = gson.toJson(user.getTags());
//        System.out.println(json);
//        user.setTags(json);
//        userMapper.update(u,)
        int i = userMapper.updateById(user);
        if (i != 1) {
            return new Result(0, "更新失败", null);
        }
        return new Result(1, "更新成功", null);

    }

    /**
     * 修改用户的标签   增减
     *
     * @param tags
     * @param request
     * @return
     */
    @RequestMapping("updateUserTags")
    public Result updateUserTags(@RequestBody List<String> tags, HttpServletRequest request) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        Gson gson = new Gson();
        user.setTags(gson.toJson(tags));
        int i = userMapper.updateById(user);
        if (i != 1) {
            return new Result(0, "更新失败", null);
        }
        return new Result(1, "更新成功", null);

    }

    /**
     * 发送验证码邮件
     *
     * @param emailOrPhone
     * @return
     */
    @PostMapping("sendCode")
    public Result sendForgetMail(
            @RequestBody String emailOrPhone
    ) {
        if ((emailOrPhone == null || emailOrPhone.trim().isEmpty())) {
            return new Result(0, "请输入邮箱或手机号码", null);
        }
        System.out.println(emailOrPhone.substring(0, emailOrPhone.indexOf("%")));
        if (emailOrPhone.contains("%")) {
            String vcode = System.currentTimeMillis() + "";
            vcode = vcode.substring(vcode.length() - 6);
            emailOrPhone = emailOrPhone.substring(0, emailOrPhone.indexOf("%")) + "@qq.com";
            System.out.println(emailOrPhone + "++++++++++" + vcode);
            emailUtil.sendSimpleMail(emailOrPhone, vcode);
            redisUtil.setT("vcode", vcode, 3 * 60);
            return new Result(1, "验证码发送成功!", vcode);
        } else {
            return new Result(1, "手机验证码发送成功", null);
        }
    }


    @GetMapping("like")
    public void like( @RequestParam String like,@RequestParam String id) {
        User user = userMapper.selectById(id);
        System.out.println(like);
        System.out.println(user.getUserAccount());
        redisUtil.set(user.getUserAccount(), Integer.parseInt(like));
        System.out.println(Integer.parseInt(like));
    }

    @Resource
    MaginformMapper maginformMapper;

    @RequestMapping("addfriend")
    public Result addFriend(HttpServletRequest request, @RequestBody Maginform maginform) {
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        //查询消息,看是不是已经发送过,3天内只能发送一次好友申请
        maginform.setSenderId(user.getId());
        LambdaQueryWrapper<Maginform> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Maginform::getSenderId, user.getId());
        lqw.eq(Maginform::getReceiverId, maginform.getReceiverId());
        lqw.orderByDesc(Maginform::getRequestTime); // 按请求时间降序排序
        lqw.last("LIMIT 1"); // 限制只取一条记录
        // 执行查询
        Maginform recentRequest = maginformMapper.selectOne(lqw);
        // 判断是否可以发送请求
        if (recentRequest != null) {
            LocalDateTime recentRequestTime = recentRequest.getRequestTime();
            LocalDateTime now = LocalDateTime.now();
            // 计算时间间隔（以天为单位）
            long daysBetween = ChronoUnit.DAYS.between(recentRequestTime, now);
            if (daysBetween >= 3) {
                // 可以发送申请
                maginformMapper.insert(maginform);
            } else {
                // 还未到3天间隔
                return new Result(0, "三天内你已经发送过了", null);
            }
        }
        // 没有之前的记录，可以发送申请
        maginformMapper.insert(maginform);
        return new Result(1, "success", null);
    }


    @RequestMapping("getinform")
    public Result getInform(HttpServletRequest request){
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        LambdaQueryWrapper<Maginform> lqw = new LambdaQueryWrapper();
        lqw.eq(Maginform::getReceiverId,user.getId());
        lqw.orderByDesc(Maginform::getRequestTime);
        List<Maginform> maginforms = maginformMapper.selectList(lqw);
        List<User> userRedis = (List<User>) redisUtil.get("userRedis");
        //数据量大时可优化
        for (Maginform m : maginforms) {
            for (User u : userRedis) {
                if ((u.getId().equals(m.getSenderId()))) {
                    m.setSendname(u.getUsername());
                    m.setImg(u.getAvatarUrl());
                }
                continue;
            }
        }
        return new Result(1,"success",maginforms);
    }
    @Resource
    FriendMapper friendMapper;

    @Transactional
    @RequestMapping("agree")
    public Result agree(HttpServletRequest request,Long senderid,String group,String magInformid){
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        Friend friend = new Friend();
        //添加好友
//        System.out.println(senderid);
        friend.setUserid(user.getId());
        friend.setFriendid(senderid);
        friend.setFrigroup(group);
//        System.out.println(friend);
        int insert = friendMapper.insert(friend);
        if (insert==1){
            //将消息设置为已同意
            friend.setUserid(senderid);
            friend.setFriendid(user.getId());
            friendMapper.insert(friend);
            Maginform maginform = maginformMapper.selectById(magInformid);
//        System.out.println(maginform);
            maginform.setStatus(1);
            maginformMapper.updateById(maginform);
        }else{
            return new Result(0,"error",null);
        }
        return new Result(1,"success",null);
    }

    @RequestMapping("getfrined")
    public Result getFriend(HttpServletRequest request){
        String token = request.getHeader("Token");
        User user = (User) redisUtil.get(token);
        LambdaQueryWrapper<Friend> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Friend::getUserid,user.getId());
        List<Friend> friends = friendMapper.selectList(lqw);
        List<User> userRedis = (List<User>) redisUtil.get("userRedis");
        //数据量大时可优化
        for (Friend friend : friends) {
            System.out.println(friend.getFriendid());
            for (User u : userRedis) {
                if ((friend.getFriendid().equals(u.getId()))) {
                    friend.setFriendname(u.getUsername());
                    System.out.println(1);
                    friend.setImg(u.getAvatarUrl());
                }
                continue;
            }
        }
        return new Result(1,"friends",friends);
    }

    @GetMapping("selectById")
    public Result selectById(@PathParam("id") String id) {
        User user = userMapper.selectById(id);
        int like = (Integer) redisUtil.get(user.getUserAccount());
        user.setLike(like);
        return new Result(1,"friend",user);
    };





    /////////////////////////////////////////////////

    /**
     * 查询所有用户
     *
     * @return
     */
    @GetMapping("getUsers")
    public List<Map<String, Object>> getUsers() {

        List<Map<String, Object>> list = userMapper.selectMaps(null);
        System.out.println(list);
        list.forEach(map -> {
            if (map.get("gender").toString().equals("0")) {
                map.put("gender", "男");
            } else {
                map.put("gender", "女");
            }
            String create_time = StringUtils.DateTimeConversion(map.get("create_time").toString());
            String update_time = StringUtils.DateTimeConversion(map.get("update_time").toString());

            map.put("create_time", create_time);
            map.put("update_time", update_time);
            if (map.get("birthday") != null) {
                String birthday = StringUtils.DateTimeConversion(map.get("birthday").toString());
                map.put("birthday", birthday.substring(0, birthday.indexOf("日")));
            }
            if (map.get("user_role").toString().equals("0")) {
                map.put("user_role", "普通用户");
            } else {
                map.put("user_role", "管理员");
            }
        });

        return list;
    }

    /**
     * 更新用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping("dongjie")
    public Result dongJie(@RequestBody User user) {
//
//        String token = request.getHeader("Token");
//        User user = (User) redisUtil.get(token);
        int i = userMapper.updateById(user);
        if (i != 1) {
            return new Result(0, "更新失败", null);
        }
        return new Result(1, "更新成功", null);
    }

    /**
     * 查询所有用户
     *
     * @return
     */
    @GetMapping("findUser")
    public List<Map<String, Object>> findUser(
            @RequestParam(name = "name") String name,
            @RequestParam(name = "phone") String phone,
            @RequestParam(name = "email") String email) {
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper();
        if (name != null) {
            lqw.like(User::getUsername, name);
        }
        if (phone != null) {
            lqw.like(User::getPhone, phone);
        }
        if (email != null) {
            lqw.like(User::getEmail, email);
        }
        List<Map<String, Object>> list = userMapper.selectMaps(lqw);
        return list;
    }

}
